#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hs/hs.h>

// 定义一个回调函数，当匹配时被调用
static int on_match(unsigned int id, unsigned long long from,
        unsigned long long to, unsigned int flags, void *ctx);

int main()
{
    // 正则表达式
    char *pat = "hello";

    // 编译正则表达式
    hs_database_t *database;
    hs_compile_error_t *compile_err;
    // 指定向量模式
    hs_error_t err = hs_compile(pat, HS_FLAG_DOTALL, HS_MODE_VECTORED,
                                NULL, &database, &compile_err);
    if (err != HS_SUCCESS) {
        fprintf(stderr, "ERROR: Unable to compile pattern \"%s\": %s\n",
                pat, compile_err->message);
        hs_free_compile_error(compile_err);
        return 1;
    }

    // 分配临时空间(指针必须初始化为NULL)
    hs_scratch_t *scratch = NULL;
    if(hs_alloc_scratch(database, &scratch) != HS_SUCCESS)
    {
        fprintf(stderr, "ERROR: Unable to allocate scratch space.
                Exiting.\n");
        hs_free_database(database);
        exit(EXIT_FAILURE);
    }

    // 单模+向量匹配
    const char *input[] = {"hello, world!", "world, hello", "hyperscan"};
    const unsigned int length[] = {strlen(input[0]), strlen(input[1]),
                                   strlen(input[2])};

    err = hs_scan_vector(database, input, length, 3, 0, scratch,
                         on_match, NULL);
    if (err != HS_SUCCESS) {
        fprintf(stderr, "Error scanning input\n");
        hs_free_scratch(scratch);
        hs_free_database(database);
        return 1;
    }

    // 释放空间
    hs_free_scratch(scratch);
    hs_free_database(database);

    return 0;
}

// 定义一个回调函数，当匹配时被调用
static int on_match(unsigned int id, unsigned long long from,
        unsigned long long to, unsigned int flags, void *ctx)
{
    printf("Match found at end offset %llu\n", to);

    return 0;
}
